<?php


namespace app\admin\service;


use app\admin\model\Token as TokenModel;

/**
 * token过期时间30天
 */
define("TOKEN_EXPIRE_TIME", 30 * 24 * 60 * 60);

class TokenService
{

    protected $token;
    protected $model;

    public function __construct(){
        $this->model = app()->make(TokenModel::class);
    }
    /**
     * 查询token，过期或者没有重新生成
     *
     * @param int $uid
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryToken(int $uid): string
    {
        $token = $this->model->where("uid", $uid)->find();
        if ($token == null || strtotime($token->expire_time) < time()) {
            return $this->insertToken($uid);
        }
        return $token->token;
    }


    public function insertToken(int $uid): string
    {
        $data['uid'] = $uid;
        $data['token'] = $this->generateToken($uid);
        // $date = (new DateTime)->setTimestamp(time() + TOKEN_EXPIRE_TIME);
        $data['expire_time'] = date("Y-m-d H:i:s", time() + TOKEN_EXPIRE_TIME);;
        $data['ip'] = get_client_ip();
        $this->model->save($data);
        return $data['token'];
    }

    /**
     * 简单生成token
     *
     * @param int $uid
     * @return string
     */
    public function generateToken(int $uid) : string {
        return md5($uid .'_'. time());
    }

    /**
     * 校验token
     *
     * @param string $token
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkToken(string $token): bool
    {
        $token = $this->model->where("token", $token)->find();
        return $token != null && strtotime($token->expire_time) > time();
    }

    /**
     * 根据token查询uid
     *
     * @param string $token
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryUidByToken(string $token): string
    {
        $token = $this->model->where("token", $token)->find();
        if ($token == null) {
            return 0;
        }
        return $token->uid;
    }
}